package com.company.cloud.club.modules.core.hander;

import com.company.cloud.club.modules.core.dto.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * 全局Controller异常处理
 *
 * @author buffge
 */
@Slf4j
@ControllerAdvice(basePackages = {
        "com.company.cloud.club"
})
@ResponseBody
public class GlobalExceptionHandler {

    @ExceptionHandler({MethodArgumentNotValidException.class})
    public Result<Object> handleValidException(MethodArgumentNotValidException ex) {
        Result<Object> res = Result.result(Result.DEFAULT_ERROR,
                ex.getBindingResult().getAllErrors().get(0).getDefaultMessage(),
                null);
        Map<Object, Object> extra = new HashMap<>();
        extra.put("errors", ex.getBindingResult().getAllErrors());
        res.setExtra(extra);
        return res;
    }

    @ExceptionHandler({Exception.class})
    public Result<Object> handleValidException(Exception ex) {
        ex.printStackTrace();
        return Result.result(Result.VALID_ERROR, ex.getMessage(), null);
    }

}